#!/bin/bash

set -euo pipefail

usage=$(cat << EOM
  Download and install amazon-ecr-credential-helper for Docker client.

  usage: $(basename $0) [-h] VERSION

  Options:
    -h  Print help message then exit

  Arguments:
    VERSION Version number of amazon-ecr-login-helper to download and install (e.g. 0.7.1)

EOM
)

function display_help {
    echo "${usage}" 1<&2
}

while getopts "h" arg; do
    case "${arg}" in
        h ) display_help
            exit 0
            ;;

        * ) display_help
            exit 1
            ;;
    esac
done
shift $((OPTIND-1))

version="${1:-}"
if [[ -z "${version}" ]]; then
    echo "❌ no version given"
    display_help
    exit 1
fi

install_path="$(dirname "$(which docker-credential-wincred.exe)")"
curl -Lo "${install_path}/docker-credential-ecr-login.exe" "https://amazon-ecr-credential-helper-releases.s3.us-east-2.amazonaws.com/${version}/windows-amd64/docker-credential-ecr-login.exe"

# Update Docker to use ecr-login instead of wincred.
modified_config="$(mktemp)"
jq '.credsStore="ecr-login"' ~/.docker/config.json > "${modified_config}"
mv -f "${modified_config}" ~/.docker/config.json
